package com.corpgovernment.common.utils;

import cn.hutool.core.util.StrUtil;
import com.ctrip.corp.obt.metric.Metrics;
import com.ctrip.corp.obt.metric.spectator.api.Id;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.concurrent.TimeUnit;

/**
 * @author ldma
 * @date 2023/9/12
 */
public class PreBookingMetricUtils {

    private static final String UNKNOWN = "unknown";

    private static final Id HOT_KEY_ID = Metrics.REGISTRY.createId("prebooking_hotkey");

    private static final Id CONDITION_QUERY_ID = Metrics.REGISTRY.createId("prebooking_condition_query");

    private static final Id HTTP_REQUEST_ID = Metrics.REGISTRY.createId("prebooking_http_request");

    /**
     * 无结果总数埋点
     */
    public static void saveNoResult() {
        Metrics.REGISTRY.counter(HTTP_REQUEST_ID
                .withTag("rpc", getRpcName())
                .withTag("code", "NoResult")).increment();
    }


    public static void saveHotCity(String city) {
        saveHotKeyId("city", city);
    }

    public static void saveHotDate(String date) {
        saveHotKeyId("date", date);
    }

    /**
     * HTTP请求量埋点
     */
    public static void saveHttpRequest(Integer code) {
        Metrics.REGISTRY.counter(HTTP_REQUEST_ID
                .withTag("rpc", getRpcName())
                .withTag("code", code == null ? UNKNOWN : String.valueOf(code))).increment();
    }

    /**
     * 条件查询埋点
     */
    public static void saveConditionQuery(Boolean conditionFlag, Long time) {
        Metrics.REGISTRY.timer(CONDITION_QUERY_ID
                .withTag("rpc", getRpcName())
                .withTag("conditionFlag", conditionFlag)).record(time, TimeUnit.MICROSECONDS);
    }

    /**
     * 热点关键词埋点
     */
    private static void saveHotKeyId(String type, String data) {
        Metrics.REGISTRY.counter(HOT_KEY_ID
                .withTag("rpc", getRpcName())
                .withTag("type", StrUtil.isEmpty(type) ? UNKNOWN : type)
                .withTag("data", StrUtil.isEmpty(data) ? UNKNOWN : data)).increment();
    }

    /**
     * 获取接口名
     */
    private static String getRpcName() {
        String rpc = UNKNOWN;
        RequestAttributes att = RequestContextHolder.getRequestAttributes();
        if (att != null) {
            rpc = ((ServletRequestAttributes) att).getRequest().getRequestURI();
        }
        return rpc;
    }

}
